package de.gameduell.framework.game.card.display {
	import flash.geom.Point;
	import de.gameduell.framework.game.card.Card;
	import de.gameduell.framework.game.card.CardStack;
	import de.gameduell.framework.geom.PointMath;	

	/**
	 * @author cbra
	 */
	public class Stack implements IDisplayMode {

		private var _offset:Point;
		private var _cardLimit:int;	
		private var _randomRotation:int;
		private var _maxDisplay:int;
		private var _randomPosition:int;
		private var lastLength:int;
		
		/**  
		 * @param aOffset         = offset of the cards to each other
		 * @param aCardLimit      = sets a limit to the cards in the stack for wich the offset is changed
		 * @param aRandomRotation = rotation of the card on the stack
		 * @param aRandomPosition = position of the card on the stack
		 * @param aMaxDisplay     = sets a limit to the number of  cards on the sack that are visible
		**/
		public function Stack(aOffset:Point,aCardLimit:int = 0,aRandomRotation:int = 0,aRandomPosition:int = 0,aMaxDisplay:int = 0) {
			_offset = aOffset;
			_cardLimit = aCardLimit;	
			_randomRotation = aRandomRotation;
			_randomPosition = aRandomPosition;
			_maxDisplay = aMaxDisplay;
//			lengthChanged = false;
			lastLength = 0;
			
		}
		
		/**  
		 * @param aLimit = sets a limit to the cards in the stack for wich the offset is changed
		**/
		public function set cardLimit(aLimit:int):void {
			_cardLimit = aLimit;
		}
		
		/**  
		 * @return Point = offset of the cards to each other
		**/
		public function get offset():Point {
			return _offset;
		}
		
		/**  
		 * @param newOffset = offset of the cards to each other
		**/
		public function set offset(newOffset:Point):void {
			_offset = newOffset;
		}
		
		/**  places the cards of the stack on the desired spots
		 * @param stack = stack on wich the cards are placed
		**/
		public function updateDisplay(stack:CardStack):void {
			var cards:Array = stack.cards;
			var tooBig:Boolean = (stack.size > _cardLimit || _cardLimit == 0 );
			var maxOffset:Point = tooBig ? PointMath.multiply(_offset, _cardLimit) : PointMath.multiply(_offset, stack.size);
		
			for (var i:Number = 0;i < stack.size; i++ ) {
				var card:Card = Card(cards[i]);
				var index:int = stack.size - i;	
				var randomized:Boolean = card.rotation != 0 ;
				stack.setChildIndex(card.sprite, i);
				var pos:Point = Point.interpolate(new Point(0, 0), maxOffset, (index / stack.size));
				card.rotation = randomized  ? card.rotation :(Math.random() * _randomRotation) -_randomRotation/2 ;
				card.position = randomized  ? card.position : pos.add(new Point((Math.random() * _randomPosition),(Math.random() * _randomPosition))) ;
				if(i == 0){
					card.rotation = 0;
					card.position = new Point(0,0);
				}
				card.scaleCard(stack.scaleFactor);
				card.visible = _maxDisplay != 0 ? stack.size-i<=_maxDisplay : true;;
			}	
		}
		

	}
}
